<template>
  <div ref="showVideoEl">
    <TopPosUIToVueUi
      :title="title"
      :to="TopPosUIToVueUiAppendTo"
      :parent-vm="selfVm"
      ref="TopPosUIToVueUiRef"
    >
      <template v-if="$slots.TopPosUIToVueUi">
        <slot name="TopPosUIToVueUi"></slot>
      </template>
    </TopPosUIToVueUi>
  </div>
</template>

<script lang="ts">
import {defineComponent, markRaw, PropType} from 'vue'
import Player, {Events} from "xgplayer";
import 'xgplayer/dist/index.min.css';
import {PLAYBACK_RATE_LIST} from "./Type.ts";
import TopPosUIToVue from "./TopPosUIToVue.ts";
import TopPosUIToVueUi from "./TopPosUIToVue.ts.vue";

export default defineComponent({
  name: 'XplayerVideo',
  components: {
    TopPosUIToVueUi
  },
  props: {
    src:String,
    playbackRate: {
      type:Number,
      default: ()=>1,
    },
    playbackRateList: {
      type:Array as PropType<PLAYBACK_RATE_LIST>,
      default: () => [3, 2.5, 2, 1.5, 1, 0.75, 0.5],
    },
    title: {
      type:String,
      default: ()=>'',
    },
    fullscreen: {
      type:Boolean,
      default: ()=>false,
    },
    cssfullscreen: {
      type:Boolean,
      default: ()=>false,
    },
  },
  created() {
    this.createdWatch(()=>this.src,()=>{
      this.player.playNext({
        url: this.src
      })
    })
    this.createdWatch(()=>this.playbackRate,()=>{
      this.player.playbackRate = this.playbackRate
    })
    this.createdWatch(()=>this.fullscreen,()=>{
      let player = this.player
      if(this.fullscreen) {
        // 播放器进入全屏状态
        player.getFullscreen()
      } else {
        player.exitFullscreen()
      }
    })
    this.createdWatch(()=>this.cssfullscreen,()=>{
      let player = this.player
      if(this.cssfullscreen) {
        // 播放器进入全屏状态
        player.getCssFullscreen()
      } else {
        player.exitCssFullscreen()
      }
    })
    this.createdWatch(()=>this.playbackRateList,()=>{
      this.player.setConfig({
        playbackRate: {
          list: this.playbackRateList
        }
      })
      let pluginRate = this.player.getPlugin('playbackRate')
      pluginRate.config.list = this.playbackRateList
      pluginRate.beforeCreate(pluginRate)
      pluginRate.renderItemList()
    })
  },
  data() {
    return {
      player: null as Player,
      TopPosUIToVueUiAppendTo: null as HTMLElement,
    }
  },
  computed: {
    selfVm() {
      return this as InstanceType<typeof this>
    }
  },
  emits: [
    'update:playbackRate',
    'update:fullscreen',
    'update:cssfullscreen',
    'loadeddata',
    'ended',
    'pause',
    'timeupdate',
  ],
  mounted() {
    let player = this.player = markRaw(new Player({
      width: '100%',
      height: '100%',
      el: this.$refs.showVideoEl,
      defaultPlaybackRate: this.playbackRate,
      mobile: {
        disablePress: false,
        pressRate: 3,
      },
      rotate:true,
    })) // markRaw 标记该对象为非响应式，即使你尝试将其转换为响应式对象，它仍然是非响应式的
    this.addTopPosUIToVueUi()
    this.player.on(Events.RATE_CHANGE,()=>{
      this.$emit('update:playbackRate',this.player.playbackRate)
    })
    this.player.on(Events.LOADED_DATA,(...args)=>{
      this.$emit('loadeddata',args)
    })
    this.player.on(Events.ENDED,(...args)=>{
      this.$emit('ended',args)
    })
    this.player.on(Events.PAUSE,(...args)=>{
      this.$emit('pause',args)
    })
    this.player.on(Events.TIME_UPDATE,(params)=>{
      this.$emit('timeupdate',params)
    })
    this.player.on(Events.FULLSCREEN_CHANGE,(fullscreen,params)=>{
      this.$emit('update:fullscreen',fullscreen)
    })
    // 监听网页全屏变化
    player.on(Events.CSS_FULLSCREEN_CHANGE, (isFullscreen) => {
      this.$emit('update:cssfullscreen',isFullscreen)
    })
  },
  methods: {
    addTopPosUIToVueUi() {
      this.player.registerPlugin(TopPosUIToVue,{
        topPosUIToVueUi: this.$refs.TopPosUIToVueUiRef
      })
      let TopPosUIToVueInstance = this.player.getPlugin('TopPosUIToVue')
      this.TopPosUIToVueUiAppendTo = TopPosUIToVueInstance.root
      // let parent = TopPosUIToVueInstance.parent as HTMLElement;
      // parent.style.height = 'auto'
      // parent.style.padding = '0'
      // const elementsByClassNameElement = parent.getElementsByClassName('controls-autohide')[0] as HTMLDivElement;
      // elementsByClassNameElement.style.width = '100%'
    },
    createdWatch(fun: Function, call: Function) {
      this.$watch(fun, (...args) => {
        if(this.player) {
          call(...args)
        } else {
          this.$nextTick(() => {
            if(this.player) {
              call(...args)
            }
          })
        }
      }, {immediate: true})
    },
    play() {
      if(this.player) {
        this.player.play()
      }
    },
    /**
     * 跳转到某个时间点继续播放，参数是number类型，单位是s(秒)（对于直播场景无效）
     * @param time
     */
    seek(time: number) {
      if (this.player) {
        this.player.seek(time)
      }
    },
    // 播放器焦点状态，控制栏显示
    focus(data?: {
      autoHide?: boolean;
      delay?: number;
      isLock?: boolean;
    }) {
      if(this.player) {
        this.player.focus(data)
      }
    },
  },
  beforeUnmount() {
    if(this.player) {
      this.player.destroy()
    }
  }
})
</script>

<style lang="scss" scoped>
.xgplayer{
  ::v-deep{
    xg-bar.xg-top-bar {
      width: 100%;
      height: auto;
      padding: 0;
      &>.controls-autohide{
        width: 100%;
      }
    }
  }
}
</style>
